package com.alibaba.dingtalk.openapi.helper;

import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.exception.OApiResultException;
import com.alibaba.dingtalk.openapi.utils.HttpHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * UserHelper
 *
 * @author kaka
 * @since V1.0
 * @date 2019/2/19 11:08
 */
public class UserHelper {

	private static final Logger LOG = LoggerFactory.getLogger(UserHelper.class);

	/**
	 * 创建成员
	 */
	public static void createUser(String accessToken, JSONObject user) throws OApiException {
		String url = Env.OAPI_HOST + "/user/create?" +
				"access_token=" + accessToken;
		HttpHelper.httpPost(url, user);
	}


	/**
	 * 更新成员
	 */
	public static void updateUser(String accessToken, JSONObject user) throws OApiException {
		String url = Env.OAPI_HOST + "/user/update?" +
				"access_token=" + accessToken;
		HttpHelper.httpPost(url, user);
	}


	/**
	 * 删除成员
	 */
	public static void deleteUser(String accessToken, String userid) throws OApiException {
		String url = Env.OAPI_HOST + "/user/delete?" +
				"access_token=" + accessToken + "&userid=" + userid;
		HttpHelper.httpGet(url);
	}


	/**
	 * 获取成员
	 */
	public static JSONObject getUser(String accessToken, String userId, String corpid) throws OApiException {
		String url = Env.OAPI_HOST + "/user/get?" +
				"access_token=" + accessToken + "&userid=" + userId;
		JSONObject responseJson = null;
		try {
			responseJson = HttpHelper.httpGet(url);
		} catch (OApiException oe) {
			if (oe.getErrCode() == 50002 || oe.getErrCode() == 60121) {
				// error code: 50002, error message: 请求的员工userid不在授权范围内
				// error code: 60121, error message: 找不到该用户
				LOG.warn("UserHelper.getUser 出错:dd-{} : corpid = {} userId={}", oe.getErrCode(), corpid, userId);
			} else {
				LOG.error("UserHelper.getUser 出错 : corpid = " + corpid + " userId=" + userId, oe);
			}
			responseJson = new JSONObject();
			responseJson.put("errcode", oe.getErrCode());
			responseJson.put("errmsg", oe.getErrMsg());
		} catch (Exception e) {
			LOG.error("UserHelper.getUser 出错 : corpid = " + corpid + " userId=" + userId, e);
		}
		return responseJson;
	}

	/**
	 * 批量删除成员
	 */
	public static void batchDeleteUser(String accessToken, List<String> useridlist)
			throws OApiException {
		String url = Env.OAPI_HOST + "/user/batchdelete?" +
				"access_token=" + accessToken;
		JSONObject args = new JSONObject();
		args.put("useridlist", useridlist);
		HttpHelper.httpPost(url, args);
	}

	/**
	 * 获取部门成员
	 */
	public static JSONArray getDepartmentUser(String accessToken, long departmentId, DingTalkPageHelper pageHelper)
			throws OApiException {
		String url = Env.OAPI_HOST + "/user/simplelist?" +
				"access_token=" + accessToken + "&department_id=" + departmentId;
		if(pageHelper != null) {
			url = url + "&offset=" + pageHelper.getOffset() + "&size=" + pageHelper.getSize();
		}
		JSONObject response = HttpHelper.httpGet(url);
		if (response.containsKey("userlist")) {
			JSONArray arr = response.getJSONArray("userlist");
			boolean hasMore = response.getBooleanValue("hasMore");
			//更新offset值
			if (Objects.nonNull(pageHelper)) {
				pageHelper.setHasMore(hasMore);
			}
			return arr;
		}
		else {
			throw new OApiResultException("userlist");
		}
	}


	/**
	 * 获取部门成员
	 */
	public static JSONArray getDepartmentUser(String accessToken, long departmentId)
			throws OApiException {
		return getDepartmentUser(accessToken, departmentId, null);
	}


	public static JSONArray getUserDetails(String accessToken, long departmentId, DingTalkPageHelper pageHelper, int retryTryTimes)
			throws OApiException {
		if (departmentId < 0 ) {
			LOG.error("getUserDetails error: departmentId <0 " + departmentId);
			return null;
		}
		String url = Env.OAPI_HOST + "/user/list?" +
				"access_token=" + accessToken + "&department_id=" + departmentId;
		if(pageHelper != null) {
			url = url + "&offset=" + pageHelper.getOffset() + "&size=" + pageHelper.getSize();
		}
		JSONObject response = new JSONObject();
		try {
			response = HttpHelper.httpGet(url);
		} catch (OApiException oe) {
			// 您的服务器调用钉钉开放平台当前接口的所有请求都被暂时禁用了（90002）, 90019单公司每秒请求次数超过40次
			// 每个ISV的套件调用单个企业的单个接口频率不可超过1000次/分，否则返回错误码90014 等待60s
			if (oe.getErrCode() == 90002 || oe.getErrCode() == 90019 || oe.getErrCode() == 90014) {
				// 90019 等待1秒钟
				long waitTimeMills = 1000;
				if (oe.getErrCode() == 90014) {
					waitTimeMills = 60000;
				}
				// 重试次数超过3次
				if (retryTryTimes >= 3) {
					LOG.error("getUserDetails 重试超过3次 "+url, oe);
					throw oe;
				} else {
					// 90019等待一秒钟再重试,90014等待一分钟再重试
					try {
						Thread.sleep(waitTimeMills);
					} catch (InterruptedException e) {
						// 恢复中断状态
						Thread.currentThread().interrupt();
						throw oe;
					}
					return getUserDetails(accessToken, departmentId, pageHelper, retryTryTimes + 1);
				}
			}else if (oe.getErrCode() == 40014) {
				//40014, error message: 不合法的access_toke
				LOG.error("getUserDetails 不合法的access_toke  "+url, oe);
				if (pageHelper != null) {
					pageHelper.setHasMore(false);
				}
			} else {
				LOG.error("getUserDetails 访问钉钉对应接口时出错，且不是90002 "+url, oe);
				if (pageHelper != null) {
					pageHelper.setHasMore(false);
				}
				throw oe;
			}
		}
		if (response != null && response.containsKey("userlist")) {
			JSONArray arr = response.getJSONArray("userlist");
			boolean hasMore = response.getBooleanValue("hasMore");
			//更新offset值
			if (pageHelper != null) {
				pageHelper.setHasMore(hasMore);
			}
			return arr;
		}
		else {
			throw new OApiResultException("userlist");
		}
	}

	/**
	 * 获取企业员工人数
	 * @param accessToken
	 * @return
	 */
	public static JSONObject getCompanyUsers(String accessToken)
			throws OApiException {
		String url = Env.OAPI_HOST + "/user/get_org_user_count?" + "access_token=" + accessToken + "&onlyActive=1";
		JSONObject response = HttpHelper.httpGet(url);
		return response;
	}

	/**
	 * 获取部门成员
	 */
	public static JSONArray getUserDetails(String accessToken, long departmentId, DingTalkPageHelper pageHelper)
			throws OApiException {
		return getUserDetails(accessToken, departmentId, pageHelper, 0);
	}


	/**
	 * 获取部门成员（详情）
	 */
	public static JSONArray getUserDetails(String accessToken, long departmentId)
			throws OApiException {
		return getUserDetails(accessToken, departmentId, null);
	}

	public static JSONObject getUserInfo(String accessToken, String code) throws OApiException{

		String url = Env.OAPI_HOST + "/user/getuserinfo?" + "access_token=" + accessToken + "&code=" + code;
		JSONObject response = HttpHelper.httpGet(url);
		return response;
	}

	public static JSONObject getAgentUserInfo(String ssoToken, String code) throws OApiException{

		String url = Env.OAPI_HOST + "/sso/getuserinfo?" + "access_token=" + ssoToken + "&code=" + code;
		JSONObject response = HttpHelper.httpGet(url);
		return response;
	}

	public static JSONObject getSNSUserInfo(String snsToken) throws OApiException{

		String url = Env.OAPI_HOST + "/sns/getuserinfo?" + "sns_token=" + snsToken;
		JSONObject response = HttpHelper.httpGet(url);
		return response;
	}

	public static void main(String[] args) {
//		String appid="dingoauoe4pkcfj8ucgmzp";
//		String appsecret="72yLLRLUQGsCLl6M5gANRZgFFOVxMiuZnB36oeB-b1s2V33xiLa4nDfRhU9Ef1D_";
//		String url1="https://oapi.dingtalk.com/sns/gettoken?appid="+appid+"&appsecret="+appsecret;
//		String corpId = "dinge3fa697f86d461d2";
//		String SSOSecret = "yFfICnqUqo4tEBq0Qra1rg-4FJSr4WLzkB3LP9piaD-22pEE1KTxCxSiUwy9R7LD";
//		String url ="https://oapi.dingtalk.com/sso/gettoken?corpid="+corpId+"id&corpsecret="+SSOSecret ;
//
//
//		try {
//			//userId+"____"+corpid
//			String t="aaq"+"____"+"xbb9831481bccfd4058925655975472c09c";
//			t = URLEncodeUtils.encodeURL(t);
//			url= DesUtil.encrypt(t, ConfigConstant.DES_DEFAULT_KEY);
//
//			System.out.println(URLEncodeUtils.decodeURL( url));
//			System.out.println("get xbbDingtalk:userAutoLogin:"+t);
//			System.out.println("http://dingtalk.xbongbong.com/user/autoLogin.do?t="+url+"&nonce=");
//
//			JedisUtils.setJedisValue("userAutoLogin", t, "123456");
//
//		} catch (Exception e) {
//
//			e.printStackTrace();
//		}
	}

}
